@tool
class_name ContextBehavior_FollowPath
extends BaseContextBehavior

## TODO 可能需要修改逻辑：路径外会提供一个指向路径的速度，路径内会提供一个使得未来位置不会离开路径的速度 

#region 属性
@export_node_path("SteeringBehaviorPath") var path:NodePath
@export var offest:Vector2
@export var prediction_t:float = 0
@export var is_arrive_enable:bool = true
@export var target_reached_threshold:float = 0.5
## 实际的到达半径是否需要加上代理半径
@export var is_target_reached_threshold_add_body_radius:bool = true
@export var slow_radius:float = 2
## 实际的减速半径是否需要加上代理半径
@export var is_slow_radius_add_body_radius:bool = true
var target_position:Vector2
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region 基类方法
func init():
	super()
func calc_steering(behaviors_owner:Node,agent:SteeringBehaviorAgent,delta:float):
	super(behaviors_owner,agent,delta)
	var sb_path = behaviors_owner.get_node_or_null(path)
	if not sb_path:
		return
	sb_path = sb_path as SteeringBehaviorPath
	var agent_current_position = agent.get_pos() + agent.get_vel() * prediction_t
	var distance = sb_path.calculate_distance(agent_current_position)
	var target_distance = distance
	if prediction_t > 0 and sb_path.is_open:
		if target_distance < sb_path.calculate_distance(agent.get_pos()):
			target_distance = sb_path.length
	target_position = sb_path.calculate_target_position(agent,self,target_distance)
	var interest = (target_position - agent.get_pos()).normalized()
	if is_arrive_enable:
		var to_target:Vector2 = target_position - agent.get_pos()
		if to_target.length() < (target_reached_threshold if not is_target_reached_threshold_add_body_radius else target_reached_threshold + agent.body_radius):
			return
		var real_slow_radius = slow_radius if not is_slow_radius_add_body_radius else slow_radius + agent.body_radius
		if to_target.length() <= real_slow_radius:
			interest *= to_target.length() / real_slow_radius
	agent.add_vel_interest(interest * sensitive)
#endregion
#region 公共方法
#endregion
#region 私有方法
#endregion
#region 生命周期函数
func _init() -> void:
	if Engine.is_editor_hint():
		resource_local_to_scene = true
	behavior_type = GameEnum.ContextBehaviorType.FollowPath
func draw() -> void:
	super.draw()
	GameSteeringBehaviorDebug.draw_circle(target_position - agent.get_pos(),target_reached_threshold if not is_target_reached_threshold_add_body_radius else target_reached_threshold + agent.body_radius,Color.RED,true)
	GameSteeringBehaviorDebug.draw_circle(agent.position,slow_radius,Color.GREEN,false,2)
#endregion
